package ru.amse.tsyganov.jumleditor.view.lines;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;

import ru.amse.tsyganov.jumleditor.graphicaleditor.Coordinates;

public class LinePainter {

	public static void drawArrowedLine(GC gc, Coordinates coordinates, Line simpleLine, boolean arrowAtStart) {
		if (simpleLine.getLength() <= 0) {
			return;
		}
		int sourceX = arrowAtStart ? simpleLine.getX1() : simpleLine.getX2();
		int sourceY = arrowAtStart ? simpleLine.getY1() : simpleLine.getY2();
		
		int targetX = arrowAtStart ? simpleLine.getX2() : simpleLine.getX1();
		int targetY = arrowAtStart ? simpleLine.getY2() : simpleLine.getY1();
	
	
		double a = Math.atan2(targetY - sourceY, 
				sourceX - targetX);
		
		double a1 = a + Math.PI / 15;
		double a2 = a - Math.PI / 15;
		double len = Math.min(13, simpleLine.getLength());
		
		gc.setAntialias(SWT.ON);
		gc.drawLine(
				coordinates.fromModelXToScreenX(simpleLine.getX1()), 
				coordinates.fromModelYToScreenY(simpleLine.getY1()),
				coordinates.fromModelXToScreenX(simpleLine.getX2()), 
				coordinates.fromModelYToScreenY(simpleLine.getY2()));
	
		gc.fillPolygon(new int[] {
				coordinates.fromModelXToScreenX(targetX + 1), 
				coordinates.fromModelYToScreenY(targetY + 1), 
				coordinates.fromModelXToScreenX((int) (targetX + len * Math.cos(a1)) + 1), 
				coordinates.fromModelYToScreenY((int) (targetY - len * Math.sin(a1)) + 1),
				coordinates.fromModelXToScreenX((int) (targetX + len * Math.cos(a2)) + 1), 
				coordinates.fromModelYToScreenY((int) (targetY - len * Math.sin(a2)) + 1)});
	}

	public static void drawArrowedLine(GC gc, Coordinates coordinates, Line[] lines) {
		for (int i = 0; i < lines.length - 1; i++) {
			gc.drawLine(
				coordinates.fromModelXToScreenX(lines[i].getX1()), 
				coordinates.fromModelYToScreenY(lines[i].getY1()), 
				coordinates.fromModelXToScreenX(lines[i].getX2()), 
				coordinates.fromModelYToScreenY(lines[i].getY2()));
		}
		drawArrowedLine(gc, coordinates, lines[lines.length - 1], true);
	}

}
